var app = require('express')();
var http = require('http').Server(app);

var io = require('socket.io')(http);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});
var roomList = [];
var roomUserInfo = {};
var roomNumber = '';

var onLineUserInfo = [];

// 当有用户进入的时候就访问这个
io.on('connection', function(socket) {
  socket.on('join', function(msg) {
    var room = roomList.indexOf(msg.roomNumber);
    //当房间不存在的情况下
    if (room === -1) {
      //房间列表添加房间
      roomList.push(msg.roomNumber);
      roomUserInfo[msg.roomNumber] = [];
    }
    var roomUserInfoIndex = roomUserInfo[msg.roomNumber].indexOf(msg.userName);
    if (roomUserInfoIndex === -1) {
      //添加房间用户
      roomUserInfo[msg.roomNumber].push(msg.userName);
      //给socket添加房间概念  所有绑定了这个房间的用户才能收到消息
    }
    socket.join(msg.roomNumber);
    socket.to(msg.roomNumber).emit('chat message', msg);
  });
  socket.on('leave', function(msg) {
    var roomUserInfoIndex = roomUserInfo[msg.roomNumber].indexOf(msg.userName);
    if (roomUserInfoIndex !== -1) {
      //添加房间用户
      roomUserInfo[msg.roomNumber].splice(roomUserInfoIndex, 1);
      //给socket添加房间概念  所有绑定了这个房间的用户才能收到消息
    }
    socket.leave(msg.roomNumber);
    socket.to(msg.roomNumber).emit('chat message', msg);
  });
  //获取调用方法
  socket.on('chat message', function(msg) {
    //给to里面的房间传递信息
    io.to(msg.roomNumber).emit('chat message', msg);
  });
  socket.on('online', function(data) {
    let fidList = data.userFriendList;
    let uid = data.userInfo.name;
    for (let index = 0; index < fidList.length; index++) {
      //因为在同一个房间内 所有可以收到相同的信息 房间号要改变一下
      //变成用户和其好友id连接的内容名称
      const fid = fidList[index];
      socket.join(`${uid}${fid}`);
      if (onLineUserInfo.indexOf(fid) === -1) {
        onLineUserInfo.push(fid);
      }
    }
  });
  socket.on('user message', function(uid, fid, msg) {
    let fonline = onLineUserInfo.indexOf(fid);
    if (fonline !== -1) {
      io.to(`${fid}${uid}`).emit('msg', uid, fid, msg);
      io.to(`${uid}${fid}`).emit('msg', uid, fid, msg);
    }
  });
});

http.listen(3000, function() {
  console.log('listening on *:3000');
});
